//
//  UserAddExpController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/9/6.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "UserAddExpController.h"
#import "FlatUIKit.h"
#import "UserItem.h"
#import "NSString+Extension.h"
#import "BRPlaceholderTextView.h"
#import "UIView+Frame.h"
#import "UserSeriesViewModel.h"


#define kUserAchieveMentMaxNum 150

@interface UserAddExpController ()<UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong) FUITextField *titleTextField;

@property (nonatomic, strong) BRPlaceholderTextView *subTextView;

@property (nonatomic, weak) UIView *contrianView;

@property (nonatomic, weak) UILabel *subLabel;

@property (nonatomic, strong) UIPickerView *pickerView;

@property (nonatomic, strong) NSArray *pickerDataSource;

/** 底部分隔线 */
@property (nonatomic, strong) UIView *bottomLineView;

@end

@implementation UserAddExpController {
    BOOL _isChinese;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isChinese = [NSBundle currentLanguageIsChinese];
    self.view.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
    
    self.pickerDataSource = [[[UserSeriesViewModel shareInstance] yearAndMonthArr].allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]]];
    
    self.title = NSLocalizedString(@"Add Achievement", @"添加成就");
    if ([NSBundle currentLangeuage] == kLanguageFrennch) {
        self.title = @"Ajouter Evènnement";
    }
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Save", @"保存") style:UIBarButtonItemStylePlain target:self action:@selector(saveExpItemClick:)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    [self setTitleTextFieldUpUI];
    [self setSubTextFieldUpUI];
    [self setPickerViewUpUI];
    
    [self configureNav];
    
    NSString *firstStr = self.pickerDataSource.lastObject;
    if (self.userItem.title.length > 0) {
        firstStr = _isChinese ?[NSString stringWithFormat:@"%@年", self.userItem.title] : self.userItem.title;
    }
    
    [self.pickerDataSource enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([firstStr isEqualToString:obj]) {
            [self.pickerView selectRow: idx inComponent:0 animated:NO];
            *stop = YES;
        }
    }];
    
    [self.titleTextField becomeFirstResponder];
}

- (void)configureNav{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sport_icon_blackbackArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveExpItemClick:(UIBarButtonItem *)item {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *titleStr = [self.titleTextField.text substringToIndex:4];

    YFUserApi *savecareer = nil;
    if (self.userItem) {
        // 修改生涯
        savecareer = [YFUserApi addOrChangeCareerWithCareerID:self.userItem.ID year:titleStr careerContent:self.subTextView.text];
    }else {
        savecareer = [YFUserApi addOrChangeCareerWithCareerID:@"" year:titleStr careerContent:self.subTextView.text];
    }
    
    [[YFNetworkingService sharedInstance] sendRequest:savecareer callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (self.selectCallback) {
                NSDictionary *dict = savecareer.responseJSONObject[@"errDesc"];
                NSLog(@"%@",dict);
                self.selectCallback(titleStr, self.subTextView.text, dict[@"ID"]);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Network unavailable, Check network", nil) afterDelay:1.0];
        }
    }];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if (![[self.titleTextField.text substringToIndex:4] isEqualToString:self.userItem.title] && self.subTextView.hasText) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
}

- (void)dealloc {
    [self.titleTextField removeObserver:self forKeyPath:@"text"];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 初始化界面
- (void)setSubTextFieldUpUI {
    
    CGSize size = [self.userItem.subTitle textSizeWithtextMaxSize:CGSizeMake(kYFScreenWidth - kAutoHei(80), MAXFLOAT) font:[UIFont systemFontOfSize:16]];
    
    if (size.height < kAutoHei(44)) {
        size = CGSizeMake(size.width, kAutoHei(44));
    }else {
        size = CGSizeMake(size.width, size.height + kAutoHei(24));
    }
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kAutoHei(66), kYFScreenWidth, size.height)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    self.contrianView = view;
    
    UILabel *leftLabel = [[UILabel alloc] init];
    leftLabel.text = NSLocalizedString(@"Achievement", @"成就");
    leftLabel.numberOfLines = 0;
    self.subLabel = leftLabel;
    
    leftLabel.textColor = [UIColor colorWithHex:0x151515];
    leftLabel.font = [UIFont systemFontOfSize:18];
    [leftLabel sizeToFit];
     CGFloat labelW = leftLabel.bounds.size.width;
    
    leftLabel.y = 0;
    leftLabel.x = 0;
    leftLabel.width = _isChinese ? (labelW + kAutoWid(40)) :(labelW + kAutoWid(16));
    
    leftLabel.height = view.height;
    leftLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:leftLabel];
    
    BRPlaceholderTextView *textView = [[BRPlaceholderTextView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftLabel.frame) + 10, 0, kYFScreenWidth - (CGRectGetMaxX(leftLabel.frame) + 10), size.height)];

    textView.textColor = [UIColor colorWithHex:0x787878];
    textView.font = [UIFont systemFontOfSize:16];
    self.subTextView = textView;
    
    textView.backgroundColor = [UIColor whiteColor];
    [view addSubview:textView];
    textView.delegate = self;
    [textView setPlaceholderColor:[UIColor lightGrayColor]];
    [textView setPlaceholderOpacity:0.6];
    textView.placeholder = _isChinese ? @"曾参加过的比赛及所获成绩" : NSLocalizedString(@"Enter the competition and awards you have attended", nil);
   
    textView.text = self.userItem.subTitle;
    
    UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(textView.frame), kYFScreenWidth, 0.5)];
    bottomLine.backgroundColor = kLineBackgroundColor;
    [view addSubview:bottomLine];
    self.bottomLineView = bottomLine;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidValueChange:) name:UITextViewTextDidChangeNotification object:nil];
    
}
- (void)setTitleTextFieldUpUI {
    FUITextField *textField = [[FUITextField alloc] initWithFrame:CGRectMake(0, kAutoHei(24), kYFScreenWidth, kAutoHei(44))];
    
    self.titleTextField = textField;
    self.titleTextField.tintColor = [UIColor clearColor];
    textField.textColor = [UIColor colorWithHex:0x787878];
    textField.font = [UIFont systemFontOfSize:16];
    
    
    textField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.titleTextField];
    textField.delegate = self;
    
    UILabel *leftLabel = [[UILabel alloc] init];
    leftLabel.text = [NSBundle currentLanguageIsChinese] ? @"年份" :([NSBundle currentLangeuage] == kLanguageFrennch ?@"Année":@"Year");
    
    leftLabel.textColor = [UIColor colorWithHex:0x151515];
    leftLabel.font = [UIFont systemFontOfSize:18];
    
    [leftLabel sizeToFit];
    CGFloat labelW = leftLabel.bounds.size.width;
    
    leftLabel.frame = CGRectMake(0, 0,(labelW + kAutoWid(40)) , kAutoHei(44));
    leftLabel.textAlignment = NSTextAlignmentCenter;
    
    self.titleTextField.leftView = leftLabel;
    self.titleTextField.leftViewMode = UITextFieldViewModeAlways;
    textField.edgeInsets = UIEdgeInsetsMake(0, kAutoWid(10), 0, 0);
    
    // 添加分隔线
    UIView *topLine = [[UIView alloc] initWithFrame:CGRectMake(0,kAutoHei(24) - 0.5, kYFScreenWidth, 0.5)];
    topLine.backgroundColor = kLineBackgroundColor;
    [self.view addSubview:topLine];
    
    NSString *firstStr = self.pickerDataSource.lastObject;
    if (self.userItem.title.length > 0) {
        firstStr = _isChinese ? [NSString stringWithFormat:@"%@年", self.userItem.title] :self.userItem.title;
    }
    self.titleTextField.text = firstStr;
    
    [self.titleTextField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
    
}


- (void)setPickerViewUpUI {
    
    UIPickerView *pickView = [[UIPickerView alloc] init];
    self.pickerView = pickView;
    pickView.dataSource = self;
    pickView.delegate = self;
    
    self.titleTextField.inputView = pickView;
    self.pickerView.backgroundColor = [UIColor whiteColor];
}

#pragma mark - UIPickerViewDelegate, UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    return self.pickerDataSource.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    return self.pickerDataSource[row];
    
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    self.titleTextField.text = self.pickerDataSource[row];
    
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(BRPlaceholderTextView *)textView {
    CGSize textSize = [textView.text textSizeWithtextMaxSize:CGSizeMake(kYFScreenWidth - kAutoHei(80), MAXFLOAT) font:[UIFont systemFontOfSize:16]];
    
    if (textSize.height < kAutoHei(44)) {
        textSize = CGSizeMake(textSize.width, kAutoHei(44));
    }else {
        textSize = CGSizeMake(textSize.width, textSize.height + kAutoHei(24));
    }
    textView.height = textSize.height;
    textView.updateHeight = textSize.height;
    self.contrianView.height = textSize.height;
    self.subLabel.height = textSize.height;
    self.bottomLineView.y = CGRectGetMaxY(textView.frame) - 0.5;
    
    
    if (textView.hasText && ![textView.text isEqualToString:self.userItem.subTitle]) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
}

- (void)textViewDidValueChange:(NSNotification *)note {
    
    if (self.subTextView.text.length <= kUserAchieveMentMaxNum) {
        
       // self.countLable.text = [NSString stringWithFormat:@"%zd", (kUserAchieveMentMaxNum - self.subTextView.text.length)];
        
    }else if (self.subTextView.text.length > kUserAchieveMentMaxNum){
       self.subTextView.text = [self.subTextView.text substringToIndex:kUserAchieveMentMaxNum];
    }
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.location >= kUserAchieveMentMaxNum) {
        //控制输入文本
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"The input words to upper limit", nil) inView:self.view];
        return  NO;
    }else{
        return YES;
    }
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return NO;
}

@end
